package com.gitee.wsl.reflect

import com.gitee.wsl.func.Function

class CopyOnWriteRef<T>(private var peek: T?, copyFunction: Function<T?, T>) {


    private var referenceCount: Int

    private val copyFunction: Function<T?, T>

    val isMutable get() = referenceCount == 0

    init {
        referenceCount = 0
        this.copyFunction = copyFunction
    }


    val immutable: T?
        get() {
            if (peek != null) referenceCount++
            return peek
        }


    val mutable: T?
        get() {
            if (referenceCount > 0) {
                peek = copyFunction.apply(peek)
                referenceCount = 0
            }
            return peek
        }

    fun setValue( value: T) {
        referenceCount = 0
        this.peek = copyFunction.apply(value)
    }

}
